/**
 * 初始化应用管理详情对话框
 */
var ApplicationInfoDlg = {
    applicationInfoData : {},
    logoSize: {},
};

/**
 * 清除数据
 */
ApplicationInfoDlg.clearData = function() {
    this.applicationInfoData = {};
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
ApplicationInfoDlg.set = function(key, val) {
    this.applicationInfoData[key] = (typeof val == "undefined") ? $("#" + key).val() : val;
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
ApplicationInfoDlg.get = function(key) {
    return $("#" + key).val();
}

/**
 * 关闭此对话框
 */
ApplicationInfoDlg.close = function() {
    parent.layer.close(window.parent.Application.layerIndex);
}

/**
 * 收集数据
 */
ApplicationInfoDlg.collectData = function() {
    this.set('appName')
        .set('appUrl')
        .set('image')
        .set('appId')
        .set('appDesc')
        .set('appAlias')
        .set('supportPush')
}

/**
 * 提交添加
 */
ApplicationInfoDlg.addSubmit = function() {

    this.clearData();
    this.collectData();

    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/application/add", function(data){
        Feng.success("添加成功!");
        window.parent.Application.table.refresh();
        ApplicationInfoDlg.close();
    },function(data){
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.applicationInfoData);
    ajax.start();
}

ApplicationInfoDlg.addApplication = function() {
    this.clearData()
    this.collectData()
    let appName = $.trim($("#appName").val());
    let appDesc = $.trim($("#appDesc").val());
    let appAlias = $.trim($("#appAlias").val());
    let supportPush = $.trim($("#supportPush").val());
    let appFile = $("#app_file")[0].files[0];
    let logo = $("#logo_file")[0].files[0];
    let {isOk ,isIpaOk,width, height} = ApplicationInfoDlg.logoSize;
    console.log(supportPush);
    if(appName === undefined || appName.length === 0) {
        layer.msg("请填写应用名称")
    } else if(appName.length > 20) {
        layer.msg("应用名称不能超过20个字符")
    } else if(appFile === null || appFile === undefined) {
        layer.msg("请上传ipa包")
    } else if(!isIpaOk){
        layer.msg("包文件格式不正确，请上传ipa包")
    } else if(logo === undefined || logo === null){
        layer.msg("请上传logo")
    } else if(!isOk) {
        layer.msg("请上传png格式图片")
    } else if(width !== 114 || height !== 114) {
        layer.msg("请上传114*114的图片")
    }else {
        let formData = new FormData();
        formData.append("appName", appName)
        formData.append("ipaFile", appFile)
        formData.append("fsImage", logo)
        formData.append("logo", logo)
        formData.append("appDesc", appDesc)
        formData.append("appAlias", appAlias)
        formData.append("supportPush", supportPush)
        let confirmIndex = layer.confirm("确定添加应用?", {
            btn: ["确认添加", "取消添加"]
        }, function () {
            layer.close(confirmIndex);
            addNewApplication(formData);
        }, function () {
            layer.msg("取消添加", {icon: 1})
        })
    }
}

/**
 *  添加应用
 * */
function addNewApplication(data) {
    //let loadIndex = layer.load(0, {shade: false})
    let loadIndex = layer.open({
        area: ['500px', '200px'],
        title: '上传文件',
        btn: []
        ,content: '<div style="display: flex; flex-direction: column;align-items: center; justify-content: center"><p id="progress">0%</p><div id="progress-slider-bg" style="height: 20px; width: 400px; background-color:lightgray;"><div id="progress-slider" style="height: 20px; background-color:#5cb75d;"></div></div></div>'
    });

    $.ajax({
        xhr: function(){
            myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){
                myXhr.upload.addEventListener('progress',function(e) {
                    if (e.lengthComputable) {
                        var percent = Math.floor(e.loaded/e.total*100);
                        let ele = document.getElementById("progress");
                        let bar = document.getElementById("progress-slider")
                        console.log(percent);
                        if(percent <= 100) {
                            ele.innerHTML = percent + "%";
                            bar.style.width = (4 * percent) + "px";
                        }
                        if(percent >= 100) {
                            ele.innerHTML = '文件上传完毕，请等待...';
                            bar.style.width = (4 * percent) + "px";
                        }
                    }
                }, false);
            }
            return myXhr;
        },
        url: Feng.ctxPath + "/application/add",
        dataType: 'json',
        type: 'POST',
        data:  data,
        processData: false,
        contentType: false,
        success: (res) => {
            layer.close(loadIndex);
            ApplicationInfoDlg.close()
            if(res.code === 200) {
                Feng.success("添加成功")
                window.parent.Application.refresh();
            } else {
                Feng.error("添加失败")
            }
        },
        error : (err) => {
            layer.close(loadIndex)
            ApplicationInfoDlg.close()
            Feng.error(err.responseJSON.message)
        }
    })
}

ApplicationInfoDlg.updateApplication = function() {
    this.clearData();
    this.collectData();
    let appFile = $("#app_file")[0].files[0];

    if(appFile === null || appFile === undefined) {
        layer.msg("请上传ipa包")
    }  else {
        let formData = new FormData();
        formData.append("ipaFile", appFile)
        let confirmIndex = layer.confirm("确定更新应用?", {
            btn: ["确认更新", "取消更新"]
        }, function () {
            layer.close(confirmIndex);
            updateNewApplication(formData);
        }, function () {
            layer.msg("取消添加", {icon: 1})
        })
    }
}

function updateNewApplication (data){
    let loadIndex = layer.open({
        area: ['500px', '200px'],
        title: '上传文件',
        btn: []
        ,content: '<div style="display: flex; flex-direction: column;align-items: center; justify-content: center"><p id="progress">0%</p><div id="progress-slider-bg" style="height: 20px; width: 400px; background-color:lightgray;"><div id="progress-slider" style="height: 20px; background-color:#5cb75d;"></div></div></div>'
    });
    //let loadIndex = layer.load(0, {shade: false})
    let appId = $.trim($("#appId").val());
    $.ajax({
        xhr: function(){
            myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){
                myXhr.upload.addEventListener('progress',function(e) {
                    if (e.lengthComputable) {
                        var percent = Math.floor(e.loaded/e.total*100);
                        let ele = document.getElementById("progress");
                        let bar = document.getElementById("progress-slider")
                        console.log(percent);
                        if(percent <= 100) {
                            ele.innerHTML = percent + "%";
                            bar.style.width = (4 * percent) + "px";
                        }
                        if(percent >= 100) {
                            ele.innerHTML = '文件上传完毕，请等待...';
                            bar.style.width = (4 * percent) + "px";
                        }
                    }
                }, false);
            }
            return myXhr;
        },
        url: Feng.ctxPath + "/application/update/" + appId,
        dataType: 'json',
        type: 'POST',
        data:  data,
        processData: false,
        contentType: false,
        success: (res) => {
            layer.close(loadIndex);
            ApplicationInfoDlg.close()
            if(res.code === 200) {
                Feng.success("更新成功")
                window.parent.Application.refresh();
            } else {
                Feng.error("更新失败")
            }
        },
        error : (err) => {
            layer.close(loadIndex)
            ApplicationInfoDlg.close()
            Feng.error(err.responseJSON.message)
        }
    })
}

function getImage() {
    let fileInput = $("#logo_file")[0];
    let file = fileInput.files[0];
    if(!isPngImagefile(fileInput.value)) {
        layer.msg("请上传png文件")
        fileInput.outerHTML = fileInput.outerHTML
    }
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (e) {
        let data = e.target.result;
        let img = new Image();
        img.src = data;
        img.onload = function () {
            ApplicationInfoDlg.logoSize.width = img.width;
            ApplicationInfoDlg.logoSize.height = img.height;
            ApplicationInfoDlg.logoSize.isOk = isPngImagefile(fileInput.value);
        }
    }
}

function getIpa() {
    let fileInput = $("#app_file")[0];
    console.log(fileInput.value);
    if(!isIpaFile(fileInput.value)) {
        layer.msg("请上传ipa文件");
        fileInput.outerHTML = fileInput.outerHTML
        return false;
    }
    ApplicationInfoDlg.logoSize.isIpaOk = isIpaFile(fileInput.value);
}

function isPngImagefile(fileName) {
    let idx = fileName.lastIndexOf(".");
    let subfix = fileName.substring(idx + 1);
    return subfix === 'png';
}

function isIpaFile(fileName) {
    let idx = fileName.lastIndexOf(".");
    let subfix = fileName.substring(idx + 1);
    return subfix === 'ipa';
}

$(function() {

});
